<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
    <title>扫地机器人清洁挑战</title>
    <style>
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            display: flex;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .game-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-right: 30px;
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        h1 {
            color: #4169E1;
            margin-bottom: 10px;
            text-align: center;
        }
        .instructions {
            margin-bottom: 20px;
            text-align: center;
            max-width: 500px;
            line-height: 1.6;
        }
        .grid {
            display: grid;
            grid-template-columns: repeat(5, 60px);
            gap: 3px;
            margin-bottom: 20px;
        }
        .cell {
            width: 60px;
            height: 60px;
            border: 2px solid #ddd;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
            position: relative;
            text-align: center;
            line-height: 1.2;
            border-radius: 5px;
        }
        .cell:hover {
            transform: scale(1.05);
            box-shadow: 0 0 8px rgba(65, 105, 225, 0.5);
        }
        .obstacle {
            background-color: #666;
            color: white;
        }
        .obstacle:hover {
            transform: none;
            box-shadow: none;
            cursor: not-allowed;
        }
        .cleaned {
            background-color: #90EE90;
        }
        .robot {
            background-color: #4169E1;
            color: white;
            font-weight: bold;
        }
        .start-point {
            background-color: #FFD700;
            font-weight: bold;
        }
        .completed {
            background-color: #90EE90;
            font-weight: bold;
            color: #4169E1;
        }
        #status {
            font-size: 18px;
            margin-bottom: 15px;
            padding: 8px 15px;
            background-color: #f0f0f0;
            border-radius: 5px;
            width: 100%;
            text-align: center;
        }
        .controls {
            margin-top: 10px;
            display: flex;
            gap: 10px;
        }
        button {
            padding: 8px 15px;
            background-color: #4169E1;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #3151B5;
        }
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            justify-content: center;
            align-items: center;
            z-index: 100;
        }
        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            max-width: 300px;
        }
        .modal h2 {
            color: #4169E1;
            margin-top: 0;
        }
        .modal button {
            margin-top: 15px;
        }
        .path-display {
            width: 450px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: #f9f9f9;
        }
        .path-item {
   	 margin-left: 20px;
   	 float: left;
            margin-bottom: 20px;
            padding: 15px;
            background-color: white;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .path-title {
            font-weight: bold;
            margin-bottom: 8px;
            color: #4169E1;
            font-size: 18px;
        }
        .path-grid {
            display: grid;
            grid-template-columns: repeat(5, 30px);
            gap: 3px;
            position: relative;
        }
        .path-cell {
            width: 30px;
            height: 30px;
            font-size: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
        }
        .path-obstacle {
            background-color: #666;
            color: white;
        }
        .path-line {
            position: absolute;
            background-color: #4169E1;
            z-index: 1;
        }
        .horizontal-line {
            height: 2px;
            top: 50%;
            transform: translateY(-1px);
        }
        .vertical-line {
            width: 2px;
            left: 50%;
            transform: translateX(-1px);
        }
        .path-visited {
            background-color: rgba(65, 105, 225, 0.2);
        }
        .path-completed {
            font-weight: bold;
            color: #4169E1;
        }
        #alertModal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #ff9800;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            z-index: 1000;
            text-align: center;
            color: white;
        }
        #alertModal button {
            margin-top: 10px;
            background-color: white;
            color: #4169E1;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
        }
        #duplicateModal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #ffeb3b;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            z-index: 1000;
            text-align: center;
        }
        #duplicateModal button {
            margin-top: 10px;
            background-color: #4169E1;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
        }
        #stuckModal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #ff5722;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            z-index: 1000;
            text-align: center;
            color: white;
        }
        #stuckModal button {
            margin-top: 10px;
            background-color: white;
            color: #4169E1;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
        }
        .tips {
            color: #FF5722;
            font-style: italic;
            margin-top: 15px;
            padding: 10px;
            background-color: #FFF8E1;
            border-radius: 5px;
            border-left: 4px solid #FFC107;
        }
        .control-hint {
            margin-top: 15px;
            color: #666;
            font-size: 14px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="game-container">
        <h1>扫地机器人清洁挑战</h1>
        <div class="instructions">
            <p>点击相邻格子控制机器人移动，必须一次完成所有22格清洁。</p>
            <p>不能重复清洁或遗漏任何格子！</p>
            <p>障碍物位置：(1,3)、(2,1)、(4,2)</p>
            <p>起点位置：(4,0)</p>
           
            <div class="control-hint">
                提示：点击机器人周围的格子进行移动
            </div>
        </div>
        <div id="status">已清洁：0/22</div>
        <div class="grid" id="grid"></div>
        <div class="controls">
            <button onclick="resetGame()">重新开始</button>
            <button onclick="undoMove()">撤销一步</button>
        </div>

        <div id="resultModal" class="modal">
            <div class="modal-content">
                <h2 id="resultTitle">结果</h2>
                <p id="resultMessage"></p>
                <button onclick="closeModal()">确定</button>
            </div>
        </div>
    </div>

    <div class="path-display" id="pathDisplay">
        <h3>已发现路径</h3>
        <div id="pathList"></div>
    </div>

    <div id="alertModal">
        <p id="alertMessage"></p>
        <button onclick="document.getElementById('alertModal').style.display='none'">确定</button>
    </div>

    <div id="duplicateModal">
        <p>路径重复！这条路线已经被发现过了。</p>
        <button onclick="document.getElementById('duplicateModal').style.display='none'">确定</button>
    </div>

    <div id="stuckModal">
        <p>还有剩余格子未清扫，重新挑战吧！</p>
        <button onclick="resetGame()">重新开始</button>
    </div>

    <audio id="successSound" src="https://assets.mixkit.co/sfx/preview/mixkit-achievement-bell-600.mp3" preload="auto"></audio>
    <audio id="failureSound" src="https://assets.mixkit.co/sfx/preview/mixkit-sad-game-over-1943.mp3" preload="auto"></audio>

    <script>
        // 游戏配置
        const GRID_SIZE = 5;
        const OBSTACLES = new Set(['1,3', '2,1', '4,2']);
        const TOTAL_PATHS = 3; // 修改为3条可行路径
        let robot = { x: 4, y: 0 }; // 修改起点为(4,0)
        let cleaned = new Set(['4,0']); // 修改起点为(4,0)
        let gameActive = true;
        let pathHistory = [{x:4, y:0}]; // 修改起点为(4,0)
        let hasFailed = false;
        let successfulPaths = [];
        let currentPathId = 1;
        let lastCleanedCell = null;

        // 音效元素
        const successSound = document.getElementById('successSound');
        const failureSound = document.getElementById('failureSound');

        // 创建网格
        function createGrid() {
            const grid = document.getElementById('grid');
            grid.innerHTML = '';
            
            for (let i = 0; i < GRID_SIZE; i++) {
                for (let j = 0; j < GRID_SIZE; j++) {
                    const cell = document.createElement('div');
                    cell.className = 'cell';
                    const key = `${i},${j}`;
                    cell.dataset.x = i;
                    cell.dataset.y = j;
                    
                    // 添加点击事件监听器
                    cell.addEventListener('click', handleCellClick);
                    
                    if (OBSTACLES.has(key)) {
                        cell.classList.add('obstacle');
                        cell.textContent = '障碍';
                    } else if (i === robot.x && j === robot.y) {
                        cell.classList.add('robot');
                        cell.textContent = '机器人';
                    } else if (i === 4 && j === 0) { // 修改起点为(4,0)
                        cell.classList.add('start-point');
                        cell.textContent = '起点';
                    } else if (cleaned.has(key)) {
                        cell.classList.add('cleaned');
                        if (lastCleanedCell && lastCleanedCell.x === i && lastCleanedCell.y === j && cleaned.size === 22) {
                            cell.classList.add('completed');
                            cell.textContent = '完成';
                        } else {
                            cell.textContent = '已清洁';
                        }
                    }
                    
                    grid.appendChild(cell);
                }
            }
            
            document.getElementById('status').textContent = `已清洁：${cleaned.size}/22`;
        }

        // 处理格子点击
        function handleCellClick(event) {
            if (!gameActive) return;
            
            const cell = event.currentTarget;
            const x = parseInt(cell.dataset.x);
            const y = parseInt(cell.dataset.y);
            
            // 检查是否点击的是障碍物
            const key = `${x},${y}`;
            if (OBSTACLES.has(key)) {
                showAlert("不能移动到障碍物！");
                return;
            }
            
            // 检查是否点击的是机器人当前位置
            if (x === robot.x && y === robot.y) {
                return;
            }
            
            // 检查是否点击的是已清洁的格子
            if (cleaned.has(key)) {
                // 检查是否点击的是上一步的位置（允许撤销）
                const lastPos = pathHistory[pathHistory.length-1];
                if (lastPos.x === x && lastPos.y === y) {
                    undoMove();
                    return;
                } else {
                    showAlert("已清洁，无法返回！");
                    return;
                }
            }
            
            // 检查是否点击的是相邻格子
            const dx = Math.abs(x - robot.x);
            const dy = Math.abs(y - robot.y);
            
            if (dx + dy !== 1) {
                showAlert("只能移动到相邻的格子！");
                return;
            }
            
            // 执行移动
            moveRobot(x, y);
            createGrid();
            checkGameState();
        }

        // 移动机器人到指定位置
        function moveRobot(x, y) {
            if (!gameActive) return false;
            
            const key = `${x},${y}`;
            
            // 检查是否碰到障碍物
            if (OBSTACLES.has(key)) {
                showAlert("触碰障碍物！");
                if (isRobotStuck()) {
                    document.getElementById('stuckModal').style.display = 'block';
                    gameActive = false;
                }
                return false;
            }
            
            // 检查移动是否合法
            if (x >= 0 && x < GRID_SIZE && y >= 0 && y < GRID_SIZE) {
                // 检查是否重复访问
                for (let i = 0; i < pathHistory.length; i++) {
                    if (pathHistory[i].x === x && pathHistory[i].y === y) {
                        showAlert("已清洁，无法返回！");
                        if (isRobotStuck()) {
                            document.getElementById('stuckModal').style.display = 'block';
                            gameActive = false;
                        }
                        return false;
                    }
                }
                
                pathHistory.push({x: x, y: y});
                robot.x = x;
                robot.y = y;
                cleaned.add(key);
                lastCleanedCell = {x: x, y: y};
                
                if (isRobotStuck() && cleaned.size < 22) {
                    document.getElementById('stuckModal').style.display = 'block';
                    gameActive = false;
                }
                
                return true;
            }
            return false;
        }

        // 撤销上一步移动
        function undoMove() {
            if (pathHistory.length <= 1) return; // 不能撤销到起点之前
            
            // 移除当前位置
            const currentPos = pathHistory.pop();
            cleaned.delete(`${currentPos.x},${currentPos.y}`);
            
            // 回到上一步位置
            const prevPos = pathHistory[pathHistory.length-1];
            robot.x = prevPos.x;
            robot.y = prevPos.y;
            
            lastCleanedCell = null;
            gameActive = true;
            hasFailed = false;
            
            createGrid();
        }

        // 显示提示框
        function showAlert(message) {
            document.getElementById('alertMessage').textContent = message;
            document.getElementById('alertModal').style.display = 'block';
        }

        // 检查路径是否重复
        function isPathDuplicate(newPath) {
            return successfulPaths.some(path => {
                if (path.history.length !== newPath.length) return false;
                return path.history.every((pos, i) => 
                    pos.x === newPath[i].x && pos.y === newPath[i].y
                );
            });
        }

        // 检查是否被困
        function isRobotStuck() {
            if (cleaned.size === 22) return false;
            
            const directions = [
                {dx: -1, dy: 0}, {dx: 1, dy: 0}, 
                {dx: 0, dy: -1}, {dx: 0, dy: 1}
            ];
            
            for (const dir of directions) {
                const newX = robot.x + dir.dx;
                const newY = robot.y + dir.dy;
                const key = `${newX},${newY}`;
                
                if (newX >= 0 && newX < GRID_SIZE && 
                    newY >= 0 && newY < GRID_SIZE &&
                    !OBSTACLES.has(key) && 
                    !cleaned.has(key)) {
                    return false;
                }
            }
            
            return true;
        }

        // 检查游戏状态
        function checkGameState() {
            if (hasFailed) return;
            
            if (cleaned.size === 22) {
                let allCleaned = true;
                for (let i = 0; i < GRID_SIZE; i++) {
                    for (let j = 0; j < GRID_SIZE; j++) {
                        const key = `${i},${j}`;
                        if (!OBSTACLES.has(key) && !cleaned.has(key)) {
                            allCleaned = false;
                            break;
                        }
                    }
                    if (!allCleaned) break;
                }
                
                if (allCleaned) {
                    const pathStr = pathHistory.map(p => `${p.x},${p.y}`).join('->');
                    const isNewPath = !isPathDuplicate(pathHistory);
                    
                    if (isNewPath) {
                        successfulPaths.push({
                            id: currentPathId++,
                            path: pathStr,
                            history: [...pathHistory]
                        });
                        displayPaths();
                        createGrid();
                        showSuccess("挑战成功！你一次完成了所有清洁！");
                    } else {
                        document.getElementById('duplicateModal').style.display = 'block';
                        gameActive = true;
                        hasFailed = false;
                    }
                } else {
                    showFailure("还有格子未清洁！");
                }
            }
        }

        // 显示所有成功路径
        function displayPaths() {
            const pathList = document.getElementById('pathList');
            pathList.innerHTML = '';
            
            successfulPaths.forEach(pathData => {
                const pathItem = document.createElement('div');
                pathItem.className = 'path-item';
                
                const title = document.createElement('div');
                title.className = 'path-title';
                title.textContent = `路线 ${pathData.id}`;
                pathItem.appendChild(title);
                
                const pathGrid = document.createElement('div');
                pathGrid.className = 'path-grid';
                
                for (let i = 0; i < GRID_SIZE; i++) {
                    for (let j = 0; j < GRID_SIZE; j++) {
                        const cell = document.createElement('div');
                        cell.className = 'path-cell';
                        const key = `${i},${j}`;
                        
                        if (OBSTACLES.has(key)) {
                            cell.classList.add('path-obstacle');
                            cell.textContent = 'X';
                        } else if (i === 4 && j === 0) { // 修改起点为(4,0)
                            cell.textContent = '起';
                        }
                        
                        pathGrid.appendChild(cell);
                    }
                }
                
                pathData.history.forEach(pos => {
                    const index = pos.x * GRID_SIZE + pos.y;
                    pathGrid.children[index].classList.add('path-visited');
                });
                
                const lastPos = pathData.history[pathData.history.length-1];
                const lastIndex = lastPos.x * GRID_SIZE + lastPos.y;
                pathGrid.children[lastIndex].classList.add('path-completed');
                pathGrid.children[lastIndex].textContent = '完';
                
                for (let k = 0; k < pathData.history.length - 1; k++) {
                    const current = pathData.history[k];
                    const next = pathData.history[k + 1];
                    
                    const index = current.x * GRID_SIZE + current.y;
                    const cell = pathGrid.children[index];
                    
                    const line = document.createElement('div');
                    line.className = 'path-line';
                    
                    if (current.x === next.x) {
                        line.classList.add('horizontal-line');
                        line.style.width = '100%';
                        if (next.y > current.y) {
                            line.style.left = '50%';
                        } else {
                            line.style.right = '50%';
                        }
                    } else {
                        line.classList.add('vertical-line');
                        line.style.height = '100%';
                        if (next.x > current.x) {
                            line.style.top = '50%';
                        } else {
                            line.style.bottom = '50%';
                        }
                    }
                    
                    cell.appendChild(line);
                }
                
                pathItem.appendChild(pathGrid);
                pathList.appendChild(pathItem);
            });
        }

        // 显示成功弹窗
        function showSuccess(message) {
            gameActive = false;
            document.getElementById('resultTitle').textContent = "挑战成功！";
            document.getElementById('resultMessage').textContent = message;
            document.getElementById('resultModal').style.display = "flex";
            successSound.currentTime = 0;
            successSound.play();
        }

        // 显示失败弹窗
        function showFailure(message) {
            gameActive = false;
            hasFailed = true;
            document.getElementById('resultTitle').textContent = "挑战失败";
            document.getElementById('resultMessage').textContent = message;
            document.getElementById('resultModal').style.display = "flex";
            failureSound.currentTime = 0;
            failureSound.play();
        }

        // 关闭弹窗
        function closeModal() {
            document.getElementById('resultModal').style.display = "none";
            resetGame();
        }

        // 重置游戏
        function resetGame() {
            robot = { x: 4, y: 0 }; // 修改起点为(4,0)
            cleaned = new Set(['4,0']); // 修改起点为(4,0)
            pathHistory = [{x:4, y:0}]; // 修改起点为(4,0)
            gameActive = true;
            hasFailed = false;
            lastCleanedCell = null;
            document.getElementById('alertModal').style.display = 'none';
            document.getElementById('duplicateModal').style.display = 'none';
            document.getElementById('stuckModal').style.display = 'none';
            createGrid();
        }

        // 初始化游戏
        createGrid();
    </script>
</body>
</html>game